import { apiGetVenueTypes } from "@/api/venueType";
import { apiGetVenueByTypeId } from '@/api/venue';
import { useErrMessage, useInfoMessage } from '@/utils/message'
import { apiCreateRez, apiFindAllRez } from "@/api/reservation";
import { apiFindMaintain } from "@/api/maintenance";

Page({
  data: {
    venueTypesInfo: {
      venue_types: [
        { id: 1, name: '羽毛球', price_per_hour: 0 },
        { id: 3, name: '篮球', price_per_hour: 0 }
      ],
      len: 2
    },
    selectedSportId: 1,   // 当前选中的运动类型ID
    selectedDate: null,  // 当前选中的日期
    todayDate: null,  // 今天的日期
    selectedSlots: [],  // 已选择的时间段
    dates: [],  // 日期数组
    timeSlots: [],  // 时间列表
    filteredVenues: [],  // 根据运动类型，过滤后的场地二维数组
    scrollHeight: 500,  // 可滚动区域高度
    totalPrice: 0,  // 总价格
    scrollTop: 0,  // 滚动位置
    slotHeight: 50, // 每个格子高度
    slotWidth: 100, // 每个格子宽度
    currentVenues: [], // 当前显示的场地数组
    currentVenueTypePricePerHour: 0, // 当前运动类型的价格
    status: [], //每个格子的状态
    unavailableSlots: [], // 不可用时间段
  },


  async onLoad() {
    this.disableTimeColumnScroll();
    this.generateWeekDates();
    this.generateTimeSlots();

    // 这是从后端获取
    await this.getVenueTypes();
    await this.getVenues();
    await this.FindAllRez();
    await this.FindMaintain();
    this.initStatus();

    // 确保在所有内容加载完成后再次计算高度
    wx.nextTick(() => {
      this.calculateHeight();
      
    });
  },

  initStatus() {
    const status = [];
    for (let j = 0; j < this.data.currentVenues.length; j++) {
      let b = [];
      for (let k = 0; k < this.data.timeSlots.length; k++) {
        const venueId = this.data.currentVenues[j].id;
        const timeSlot = this.data.timeSlots[k];

        let isUnavailable = false;

        // 检查是否是今天的时间段，且时间已经过去
        if (this.data.selectedDate === this.data.todayDate) {
          const now = new Date();
          const currentHour = now.getHours();
          const currentMinute = now.getMinutes();
          
          // 解析时间段的小时
          const slotHour = parseInt(timeSlot.startTime.split(':')[0]);
          
          // 如果当前小时大于时间段开始小时，或者当前小时等于时间段开始小时但分钟已过，则标记为不可用
          if (currentHour > slotHour || (currentHour === slotHour && currentMinute > 0)) {
            // console.log(currentHour,slotHour);
            
            isUnavailable = true;
          }
        }

        // 检查是否与已有的不可用时间段重叠
        if (!isUnavailable && this.data.unavailableSlots.length > 0) {
          isUnavailable = this.data.unavailableSlots.some(slot => {
            const slotStartTime = slot.startTime.replace("T", " ").split("+")[0];
            const slotEndTime = slot.endTime.replace("T", " ").split("+")[0];
            
            // 当前时间段的开始和结束时间
            const currentStartTime = `${this.data.selectedDate} ${timeSlot.startTime}:00`;
            const currentEndTime = `${this.data.selectedDate} ${timeSlot.endTime}:00`;
            
            // 检查是否是同一个场地
            if (slot.venueId !== venueId) {
              return false;
            }
            
            // 检查时间是否重叠
            // 情况1：不可用时段的开始时间在当前时段内
            // 情况2：不可用时段的结束时间在当前时段内
            // 情况3：当前时段完全被不可用时段包含
            return (
              (slotStartTime >= currentStartTime && slotStartTime < currentEndTime) ||
              (slotEndTime > currentStartTime && slotEndTime <= currentEndTime) ||
              (slotStartTime <= currentStartTime && slotEndTime >= currentEndTime)
            );
          });
        }

        b.push(isUnavailable ? 'unavailable' : 'available');
      }
      status.push(b);
    }
    this.setData({
      status: status
    });
  },

  async FindMaintain() {
    try {
      const today = new Date(this.data.todayDate);
      const nextWeek = new Date(today);
      nextWeek.setDate(today.getDate() + 7); // 一周后的日期

      const res = await apiFindMaintain({
        page: 1,
        pageSize: 100,
        startTime: this.data.todayDate,
        endTime: nextWeek.toISOString().split('T')[0]
      });

      
      if (res.code === 200 && res.data.maintenances.length > 0) {
        const unavailableSlots = res.data.maintenances.map(item => ({
          venueId: item.venue_id,
          startTime: item.start_time,
          endTime: item.end_time
        }));

        this.setData({ unavailableSlots: [...this.data.unavailableSlots, ...unavailableSlots] });

      }
    } catch (error) {
      useErrMessage(this, '获取预约数据失败，请重试');
    }
  },

  async FindAllRez() {
    try {
      const res = await apiFindAllRez({
        page: 1,
        pageSize: 100,
        startTime: this.data.todayDate
      });


      if (res.code === 200 && res.data.reservations.length > 0) {
        const unavailableSlots = res.data.reservations.map(item => ({
          venueId: item.venue_id,
          startTime: item.start_time,
          endTime: item.end_time
        }));

        this.setData({ unavailableSlots: [...this.data.unavailableSlots, ...unavailableSlots] });
      }

    } catch (error) {
      useErrMessage(this, '获取预约数据失败，请重试');
    }
  },


  /////////////////////////////////////////////////////
  // 获取格子的日期，开始时间，结束时间
  getSlotKey(venue, timeIndex) {
    const timeSlot = this.data.timeSlots[timeIndex];

    return `${this.data.selectedDate},${venue.id},${timeSlot.startTime},${timeSlot.endTime}`;
  },



  // 选择时间段
  selectSlot(e) {
    const { start, end, venue } = e.currentTarget.dataset;
    const venueObj = this.data.currentVenues.find(v => v.id == venue);
    const venueIndex = this.data.currentVenues.findIndex(v => v.id == venue);

    const timeIndex = this.data.timeSlots.findIndex(t => t.startTime === start);
    const slotKey = this.getSlotKey(venueObj, timeIndex);

    let selectedSlots = [...this.data.selectedSlots];
    const index = selectedSlots.findIndex(s => s.key === slotKey);
    const price = this.data.currentVenueTypePricePerHour;

    if (index === -1) {
      selectedSlots.push({
        key: slotKey,
        date: this.data.selectedDate,
        venue: venueObj,
        startTime: start,
        endTime: end,
        price: price
      });

      this.data.status[venueIndex][timeIndex] = 'selected'; // 更新状态为已选择
    } else {
      selectedSlots.splice(index, 1);
      this.data.status[venueIndex][timeIndex] = 'available'; // 恢复状态为可预订
    }

    const totalPrice = selectedSlots.reduce((sum, slot) => sum + slot.price, 0);

    this.setData({
      selectedSlots,
      totalPrice,
      status: this.data.status // 更新状态
    });
  },

  // 提交预订
  async submitBooking() {
    if (this.data.selectedSlots.length === 0) return;

    wx.showModal({
      title: '确认预订',
      content: `您将预订 ${this.data.selectedSlots.length} 个时间段，总价 ${this.data.totalPrice} 元`,
      success: async (res) => {
        if (res.confirm) {
          try {
            const bookingPromises = this.data.selectedSlots.map(async (slot) => {
              const formattedStartTime = `${slot.date} ${slot.startTime}:00`;
              const formattedEndTime = `${slot.date} ${slot.endTime}:00`;
              const requestData = {
                venueId: slot.venue.id,
                startTime: formattedStartTime,
                endTime: formattedEndTime,
                week: new Date(slot.date).getDay(), // 获取星期几
                mode: 1,
                amount: slot.price
              };

              const res = await apiCreateRez(requestData);
              if (res.code !== 200) {
                useErrMessage(this, res.msg);
                throw new Error(`预订场地 ${slot.venue.id} 失败`);
              }
            });

            // 等待所有预订请求完成
            await Promise.all(bookingPromises);

            wx.showToast({
              title: '预订成功',
              icon: 'success'
            });
            this.setData({
              selectedSlots: [],
              totalPrice: 0
            });
            this.showProcessing();
            setTimeout(() => {
              wx.hideLoading();
              this.onLoad();
            }, 5500);
          } catch (error) {
            console.error('预订失败:', error);
            useErrMessage(this, '预订失败，请重试');
          }
        }
      }
    });
  },
  showProcessing() {
    wx.showLoading({
      title: '执行中...',
      mask: true,          // 透明遮罩层，阻止触摸穿透
    });
  },

  // 获取运动类型列表
  async getVenueTypes() {
    const data = await apiGetVenueTypes()
    if (data.code === 200) {
      this.setData({
        venueTypesInfo: data.data
      })
    } else {
      useErrMessage(this, data.msg)
    }
  },

  // 获取场地
  async getVenues() {
    try {
      const promises = this.data.venueTypesInfo.venue_types.map(async (obj) => {
        const res = await apiGetVenueByTypeId(obj.id);
        if (res.code !== 200) {
          console.error(`获取类型 ${obj.id} 场地失败`, res);
          return null;
        }
        return {
          typeId: obj.id,          // 运动类型ID
          typeName: obj.name,      // 运动类型名称
          venues: res.data.venues,  // 对应场地数组
          pricePerHour: obj.price_per_hour // 运动类型价格
        };
      });

      const results = await Promise.all(promises);


      this.setData({
        filteredVenues: results.filter(Boolean),
        currentVenues: results.find(r => r.typeId === this.data.selectedSportId)?.venues || []
      });

    } catch (error) {
      console.error('获取场地数据失败:', error);
    }
  },

  // 选择运动
  selectSport(e) {
    const { id } = e.currentTarget.dataset;
    this.setData({
      selectedSportId: id,
      selectedSlots: [],
      totalPrice: 0
    }, () => {

      const targetCategory = this.data.filteredVenues.find(item => item.typeId == id);
      const venues = targetCategory ? targetCategory.venues : [];

      this.setData({
        currentVenues: venues,
        currentVenueTypePricePerHour: targetCategory ? targetCategory.pricePerHour : 0
      });

      this.initStatus();
    });
  },

  // 选择日期
  async selectDate(e) {
    this.setData({
      selectedDate: e.currentTarget.dataset.date,
      selectedSlots: [],
      totalPrice: 0
    });

    this.initStatus();
  },

  // 唯一滚动事件处理
  onVenuesScroll(e) {
    this.setData({
      scrollTop: e.detail.scrollTop
    });
  },

  // 禁用时间列触摸事件
  disableTimeColumnScroll() {
    const query = wx.createSelectorQuery();
    query.select('.time-column').fields({
      size: true,
      scrollOffset: true
    });
    query.exec(() => {
      // 通过设置样式确保无法滚动
      this.setData({
        'timeColumnStyle': 'overflow:hidden;touch-action:none;'
      });
    });
  },

  // 生成日期
  generateWeekDates() {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const today = new Date();
    const dates = [];

    for (let i = 0; i < 7; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);

      const month = date.getMonth() + 1;
      const day = date.getDate();
      const dayOfWeek = date.getDay();
      const fullDate = date.toLocaleString('zh-CN',
        {
          timeZone: 'Asia/Shanghai',
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        }).split(' ')[0].replace(/\//g, '-');
      dates.push({
        dayText: i === 0 ? '今天' : days[dayOfWeek],
        date: `${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`,
        fullDate: fullDate
      });
    }

    this.setData({
      dates,
      selectedDate: dates[0].fullDate,
      todayDate: dates[0].fullDate
    });
  },

  // 生成时间列表
  generateTimeSlots() {
    const slots = [];
    for (let hour = 7; hour <= 23; hour++) {
      const startTime = `${hour < 10 ? '0' + hour : hour}:00`;
      const endTime = `${hour + 1 < 10 ? '0' + (hour + 1) : hour + 1}:00`;
      slots.push({ startTime, endTime });
    }
    // console.log(slots);
    this.setData({ timeSlots: slots });
  },

  calculateHeight() {
    const windowInfo = wx.getWindowInfo();
    const query = wx.createSelectorQuery();

    query.select('.footer').boundingClientRect();
    query.select('.date-scroll').boundingClientRect();
    query.select('.sport-scroll').boundingClientRect();

    query.exec(res => {
      const windowHeight = windowInfo.windowHeight;
      const footerHeight = res[0].height;
      const dateHeight = res[1].height;
      const sportHeight = res[2].height;

      const availableHeight = windowHeight - footerHeight - dateHeight - sportHeight - 100;

      
      this.setData({
        scrollHeight: availableHeight
      });
    });
  }
});
/////////////////////////////////////////////